﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Money.Data;
using One.Framework;
using Money.Interfaces;
using One.Web;

public partial class Admin_TransactionManagement : System.Web.UI.Page
{
    #region fields

    private ITransactionService transactionService;
    private IAccountService accountService;
    protected List<Transaction> listTransactions;
    private TransactionOrderBy orderBy;
    private OrderDirection orderDirection;
    private string redirectUrl = "TransactionManagement.aspx";
    private int success;
    private string errorIds;
    private int totalRecords;
    private List<Account> accountList;
    private int accountFrom;
    private int accountTo;
    private string payMan;
    private int transactionType;

    #endregion

    #region events

    protected void Page_Load(object sender, EventArgs e)
    {
        transactionService = ServiceFactory.Create<ITransactionService>();
        accountService = ServiceFactory.Create<IAccountService>();

        GetParams();
        LoadData();
        if (!IsPostBack)
            UpdateView();
    }

    protected void Search(object sender, EventArgs e)
    {
        List<One.Web.QueryStringParameter> listParam = new List<One.Web.QueryStringParameter>();
        accountFrom = int.Parse(cbAccount.SelectedValue);
        accountTo = int.Parse(cbAccountTo.SelectedValue);
        payMan = tbPayMan.Text;
        transactionType = int.Parse(cbTransactionType.SelectedValue);

        if (transactionType != 0)
        {
            listParam.Add(new One.Web.QueryStringParameter("type", transactionType.ToString()));
        }
        if(accountFrom != 0)
            listParam.Add(new One.Web.QueryStringParameter("from", accountFrom.ToString()));
        if (transactionType == (int)TransactionType.Transfer && accountTo != 0)
            listParam.Add(new One.Web.QueryStringParameter("to", accountTo.ToString()));
        if(!string.IsNullOrEmpty(payMan))
            listParam.Add(new One.Web.QueryStringParameter("payman", payMan));
        string paramUrl = QueryStringUtility.BuildQueryString(listParam);
        if (!string.IsNullOrEmpty(paramUrl))
        {
            Response.Redirect(string.Format("{0}?{1}", redirectUrl, paramUrl));
        }
        Response.Redirect(redirectUrl);    
    }

    protected void ChangeTransactionType(object sender, EventArgs e)
    {
        divAccountTo.Visible = false;
        switch (int.Parse(cbTransactionType.SelectedValue))
        {
            case (int)TransactionType.Deposit:
                labelAccount.Text = Resources.Strings.ToAccount;
                break;
            case (int)TransactionType.Payment:
                labelAccount.Text = Resources.Strings.FromAccount;
                break;
            case (int)TransactionType.Transfer:
                labelAccount.Text = Resources.Strings.FromAccount;
                divAccountTo.Visible = true;
                break;
            default:
                labelAccount.Text = Resources.Strings.Account;
                divAccountTo.Visible = false;
                break;
        }
    }

    protected void DeleteTransactions(object sender, EventArgs e)
    {
        string[] deleteIdString;
        string idError = "";
        if (string.IsNullOrEmpty(Request.Form["selectedItems"]))
        {
            return;
        }
        deleteIdString = Request.Form["selectedItems"].Split(',');
        for (int i = 0; i < deleteIdString.Length; i++)
        {
            long id = 0;
            try
            {
                if (!long.TryParse(deleteIdString[i], out id))
                    id = 0;
                transactionService.DeleteTransaction(id);
            }
            catch
            {
                if (id != 0)
                    idError = string.Format("{0},{1}", idError, id);
            }
        }
        if (!string.IsNullOrEmpty(idError))
        {
            idError = idError.TrimStart(',');
            Response.Redirect(string.Format("{0}?success={1}&idserror={2}", redirectUrl, -3, idError));
        }
        else
        {
            Response.Redirect(string.Format("{0}?success={1}", redirectUrl, 3));
        }
    }

    #endregion

    #region private functions

    private void GetParams()
    {
        orderBy = QueryStringUtility.GetEnum<TransactionOrderBy>("orderBy", TransactionOrderBy.Id.ToString());
        orderDirection = QueryStringUtility.GetEnum<OrderDirection>("orderDirection", OrderDirection.ASC.ToString());
        success = QueryStringUtility.GetInt32("success", 0);
        errorIds = QueryStringUtility.GetString("idserror", string.Empty);
        accountFrom = QueryStringUtility.GetInt32("from", 0);
        accountTo = QueryStringUtility.GetInt32("to", 0);
        transactionType = QueryStringUtility.GetInt32("type", 0);
        payMan = QueryStringUtility.GetString("payman", string.Empty);
    }

    private void LoadData()
    {
        string strOrderBy = orderBy.ToString();
        if(orderBy == TransactionOrderBy.Account || orderBy == TransactionOrderBy.Category || orderBy == TransactionOrderBy.Ref || orderBy == TransactionOrderBy.Class)
            strOrderBy = string.Format("{0}.{1}", strOrderBy, orderBy == TransactionOrderBy.Account ? "DisplayName" : "Name");
        listTransactions = transactionService.GetTransactions(WebSession.CurrentUser.UserId, accountFrom , accountTo, transactionType, payMan, strOrderBy, orderDirection.ToString(), pager.PageIndex,
                                MoneyManagerConfig.AdminPageSize, out totalRecords);
        accountList = accountService.GetAccounts(WebSession.CurrentUser.UserId, AccountOrderBy.DisplayName.ToString(), OrderDirection.ASC.ToString());
        accountList.Insert(0, new Account() { DisplayName = "All", AccountId = 0 });
    }

    private void UpdateView()
    {
        AddTransactionType();
        AddFromAccounts();
        AddToAccounts();
        repeaterTransactions.DataSource = listTransactions;
        repeaterTransactions.DataBind();

        (Master as Admin_MasterPage).SelectedTab = "transactionManagement";
        pageTitle.Text = Resources.Strings.TransactionManagement;
        pager.TotalRecords = totalRecords;
        pager.PageSize = MoneyManagerConfig.AdminPageSize;

        messageLabel.Visible = success != 0;

        switch (success)
        {
            case 1:
                messageLabel.Text = Resources.Strings.AddTransactionSuccess;
                break;
            case 2:
                messageLabel.Text = Resources.Strings.UpdateTransactionSuccess;
                break;
            case 3:
                messageLabel.Text = Resources.Strings.DeleteTransactionSuccess;
                break;
            case -1:
                messageLabel.Text = Resources.Strings.AddTransactionUnSuccess;
                break;
            case -2:
                messageLabel.Text = Resources.Strings.UpdateTransactionUnSuccess;
                break;
            case -3:
                messageLabel.Text = string.Format(Resources.Strings.DeleteTransactionUnSuccess, errorIds);
                break;

        }
        cbAccountTo.SelectedValue = accountTo.ToString();
        cbAccount.SelectedValue = accountFrom.ToString();
        cbTransactionType.SelectedValue = transactionType.ToString();
        tbPayMan.Text = payMan;
        ChangeTransactionType(null, null);
    }

    private void AddFromAccounts()
    {
        
        cbAccount.DataSource = accountList;
        cbAccount.DataTextField = "DisplayName";
        cbAccount.DataValueField = "AccountId";
        cbAccount.DataBind();
    }

    private void AddToAccounts()
    {
        cbAccountTo.DataSource = accountList;
        cbAccountTo.DataTextField = "DisplayName";
        cbAccountTo.DataValueField = "AccountId";
        cbAccountTo.DataBind();
    }

    private void AddTransactionType()
    {
        List<KeyValuePair<int, string>> list = MoneyUtilities.GetEnumList(typeof(TransactionType));
        list.Insert(0, new KeyValuePair<int, string>(0, "All"));
        cbTransactionType.DataSource = list;
        cbTransactionType.DataTextField = "Value";
        cbTransactionType.DataValueField = "Key";
        cbTransactionType.DataBind();
    }

    #endregion

    #region public functions

    public string GetOrderByLink(string propertyName)
    {
        OrderDirection newOrderDirection = orderDirection;
        string url = CreateUrlParams();
        if (propertyName == orderBy.ToString())
        {
            newOrderDirection = orderDirection == OrderDirection.ASC ? OrderDirection.DESC : OrderDirection.ASC;
        }
        return String.Format("{0}{4}OrderBy={1}&OrderDirection={2}&Page={3}", url,
            propertyName, newOrderDirection.ToString(), pager.PageIndex, url.IndexOf('?') > 0 ? "&" : "?");
    }

    private string CreateUrlParams()
    {
        return redirectUrl;
    }

    public string GetOrderDirectionIndicator(string propertyName)
    {
        if (propertyName == orderBy.ToString())
        {
            return String.Format("<img src=\"../images/{0}.gif\" alt=\"{0}\" align=\"absmiddle\" />", orderDirection);
        }
        return "";
    }

    public string GetNameTransactionType(object value)
    {
        try
        {
            return Enum.GetName(typeof(TransactionType), value);
        }
        catch
        {
            return string.Empty;
        }
    }

    #endregion
}
